<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import type { CaptchaResponse } from '@/types/auth'
import { authService } from '@/services/auth'
import { useNotification } from '@/composables/useNotification'
import '@/assets/styles/components/captcha-verify.css'

const notify = useNotification()

interface Props {
  /** 是否显示验证码 */
  visible: boolean
  /** 验证码输入框样式 */
  inputStyle?: Record<string, string>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'verify-success', captchaId: string): void
  (e: 'verify-failed'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  inputStyle: () => ({
    width: '100%',
    height: '48px',
    borderRadius: '12px',
  }),
})

const emit = defineEmits<Emits>()

const captchaInfo = ref<CaptchaResponse | null>(null)
const captchaCode = ref('')

// 获取验证码
const getCaptcha = async () => {
  try {
    const response = await authService.generateCaptcha()
    captchaInfo.value = response
  } catch (error) {
    notify.error(error instanceof Error ? error.message : '获取验证码失败')
  }
}

// 验证验证码
const verifyCaptcha = async () => {
  if (!captchaInfo.value || !captchaCode.value) return false

  try {
    await authService.verifyCaptcha({
      captchaId: captchaInfo.value.captchaId,
      captchaCode: captchaCode.value,
    })
    // 验证码验证通过后，触发成功事件
    emit('verify-success', captchaInfo.value.captchaId)
    return true
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '验证码验证失败'
    notify.error(errorMessage, {
      title: '验证失败',
    })
    // 验证码验证失败时，刷新验证码
    getCaptcha()
    captchaCode.value = ''
    emit('verify-failed')
    return false
  }
}

// 监听visible变化
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      getCaptcha()
    } else {
      captchaCode.value = ''
      captchaInfo.value = null
    }
  },
  { immediate: true },
)

// 组件挂载时如果 visible 为 true，则获取验证码
onMounted(() => {
  if (props.visible) {
    getCaptcha()
  }
})
</script>

<template>
  <div v-if="visible" class="flex space-x-2 captcha-input">
    <a-input
      v-model="captchaCode"
      placeholder="请输入验证码"
      :style="inputStyle"
      allow-clear
      @keyup.enter="verifyCaptcha"
      @blur="verifyCaptcha"
    />
    <div
      class="w-32 h-12 cursor-pointer flex-shrink-0 border rounded-xl overflow-hidden"
      @click="getCaptcha"
    >
      <img
        v-if="captchaInfo?.captchaImage"
        :src="captchaInfo.captchaImage"
        alt="验证码"
        class="w-full h-full object-contain"
      />
      <div v-else class="w-full h-full flex items-center justify-center text-gray-400 bg-gray-50">
        加载中...
      </div>
    </div>
  </div>
</template>
